//
//  GPTopUpViewController.m
//  大股票
//
//  Created by mac on 2019/9/5.
//  Copyright © 2019 apple. All rights reserved.
//

#import "GPTopUpViewController.h"
#import "GPTopUpResultVC.h"
#import "GPAccountModel.h"
#import "DGPUtil.h"
#import <StoreKit/StoreKit.h>

#define kProductIDArr @[@"com.gupiaopeizi_100", @"com.gupiaopeizi_300",@"com.gupiaopeizi_500",@"com.gupiaopeizi_800",@"com.gupiaopeizi_1000",@"com.gupiaopeizi_2000"]

@interface GPTopUpViewController ()<SKPaymentTransactionObserver,SKProductsRequestDelegate>

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *moneyBtnArr;

@property (nonatomic, strong) UIButton *selectedBtn;

@end

@implementation GPTopUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[SKPaymentQueue defaultQueue]addTransactionObserver:self];
    
    [self updateUI];
}

- (void)updateUI {
    
    for (UIButton *btn in self.moneyBtnArr) {
        [btn setBackgroundImage:[[UIImage imageNamed:@"m未选中"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [btn setBackgroundImage:[[UIImage imageNamed:@"m选中"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateSelected];

    }
    //默认选择最后一个
    [self seletedMoneyWithBtn:self.moneyBtnArr.lastObject];
}

- (IBAction)topUpAction:(id)sender {
    if ([SKPaymentQueue canMakePayments]) {
        NSLog(@"支持苹果支付");
        NSInteger index = [self.moneyBtnArr indexOfObject:self.selectedBtn];
        NSString *productID = kProductIDArr[index];
        
        SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithArray:@[productID]]];
        request.delegate = self;
        [request start];
        [self showLoadingAnimatedToView:WINDOW];
    }else{
        NSLog(@"不支持苹果支付");
    }
    
    
//    [self successfulAction];

}

- (IBAction)btnAction:(UIButton *)sender {
    
    [self seletedMoneyWithBtn:sender];
}

#pragma mark - 选择金钱
- (void)seletedMoneyWithBtn:(UIButton *)btn {
    if (btn == self.selectedBtn) {
        return;
    }
    
    //重置
    self.selectedBtn.selected = NO;
    
    btn.selected = YES;
    
    self.selectedBtn = btn;
}

//充值成功
-(void)successfulAction{
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [DGPUtil calculatemoney:@"充值" by:[self.selectedBtn.titleLabel.text floatValue] successCallback:^{
            [weakSelf addRecord];
            GPTopUpResultVC *resultVC = [[GPTopUpResultVC alloc] init];
            resultVC.navTitle = @"充值成功";
            resultVC.money = weakSelf.selectedBtn.titleLabel.text;
            [weakSelf.navigationController pushViewController:resultVC animated:YES];
        } failedCallback:^{
            
        }];
    });
    
}

-(void)addRecord{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    GPAccountModel *model = [[GPAccountModel alloc] init];
    model.type = 1;
    model.money = self.selectedBtn.titleLabel.text;
    model.date = [dateFormatter stringFromDate:[NSDate date]];
    model.status = @"充值成功";
    NSMutableArray *muArr = [NSMutableArray arrayWithArray:[USER_DEFAULTS objectForKey:[NSString stringWithFormat:@"%@_topList",[DGPUtil getCurrentUserID]]]];
    [muArr addObject:model.mj_JSONObject];
    NSArray *array = muArr;
    [USER_DEFAULTS setObject:array forKey:[NSString stringWithFormat:@"%@_topList",[DGPUtil getCurrentUserID]]];
}

#pragma mark - SKProductsRequestDelegate
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    if (response.invalidProductIdentifiers.count > 0) {
        [MBProgressHUD showInformation:@"ProductID Fail" toView:self.view andAfterDelay:HUD_TIME];
        [self dismissLoadingAnimatedToView];
    }else{
        //取到内购产品进行购买
        SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:response.products.firstObject];
        NSArray* transactions = [SKPaymentQueue defaultQueue].transactions;
        if (transactions.count > 0) {
            //检测是否有未完成的交易
            SKPaymentTransaction* transaction = [transactions firstObject];
            if (transaction.transactionState == SKPaymentTransactionStatePurchased) {
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                return;
            }
        }
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
}

//交易结束
- (void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
    
    NSLog(@"交易结束");
    self.view.userInteractionEnabled = YES;
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
    
}

#pragma mark - SKPaymentTransactionObserver
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased://购买成功
                //                [self dismissLoadingAnimatedToView];
                [self dl_completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed://购买失败
                [self dismissLoadingAnimatedToView];
                [self dl_failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored://恢复购买
                [self dismissLoadingAnimatedToView];
                [self dl_restoreTransaction:transaction];
                break;
            case SKPaymentTransactionStatePurchasing://正在处理
                break;
            default:
            {
                NSLog(@"");
            }
                break;
        }
    }
    
}

#pragma mark - PrivateMethod
- (void)dl_completeTransaction:(SKPaymentTransaction *)transaction {
    NSString *productIdentifier = transaction.payment.productIdentifier;
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    
    NSString *receipt=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
    if ([receipt length] > 0 && [productIdentifier length] > 0) {
        
//        [MBProgressHUD showInformation:@"Purchase success! " toView:WINDOW andAfterDelay:HUD_TIME];
        /**
         可以将receipt发给服务器进行购买验证
         */
        [self dl_validateReceiptWiththeAppStore:receipt];
        
    }else{
        [self dismissLoadingAnimatedToView];
    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void)dl_failedTransaction:(SKPaymentTransaction *)transaction {
    if(transaction.error.code != SKErrorPaymentCancelled) {
        
        [MBProgressHUD showInformation:@"Your payment is cancelled." toView:WINDOW andAfterDelay:HUD_TIME];
        [self dismissLoadingAnimatedToView];
    } else {
//        [MBProgressHUD showInformation:@"购买失败" toView:WINDOW andAfterDelay:HUD_TIME];
        [self dismissLoadingAnimatedToView];
    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}


- (void)dl_restoreTransaction:(SKPaymentTransaction *)transaction {
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

//本地去AppStore验证
-(void)dl_validateReceiptWiththeAppStore:(NSString *)receipt
{
    
    
    
        NSError *error;
        NSDictionary *requestContents = @{@"receipt-data": receipt};
        NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents options:0 error:&error];
    
        if (!requestData) {
    
        }else{
    
        }
        NSURL *storeURL;
    #ifdef DEBUG
        storeURL = [NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"];
    #else
        storeURL = [NSURL URLWithString:@"https://buy.itunes.apple.com/verifyReceipt"];
    #endif
    
        NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:storeURL];
        [storeRequest setHTTPMethod:@"POST"];
        [storeRequest setHTTPBody:requestData];
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [NSURLConnection sendAsynchronousRequest:storeRequest queue:queue
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                   dispatch_async(dispatch_get_main_queue(), ^{
                                       [self dismissLoadingAnimatedToView];
                                       if (connectionError) {
                                           /* 处理error */
                                           // 无法连接服务器,购买校验失败
                                       } else {
                                           NSError *error;
                                           NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                                           if (!jsonResponse) {
                                               /* 处理error */
                                               // 苹果服务器校验数据返回为空校验失败
                                           }else{
                                               /* 处理验证结果 */
                                               NSString *status = [NSString stringWithFormat:@"%@",jsonResponse[@"status"]];
                                               //                                       [self netRequest];
                                               if ([status isEqualToString:@"0"]) {
                                                   [self successfulAction];
                                               }
                                           }
                                       }
                                   });
                                   
                               }];
    //从沙盒中获取交易凭证并且拼接成请求体数据
    //    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    //    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    //
    //    NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
    
//    NSString *storeURL;
//#ifdef DEBUG
//    storeURL = @"https://sandbox.itunes.apple.com/verifyReceipt";
//#else
//    storeURL = @"https://buy.itunes.apple.com/verifyReceipt";
//#endif
//    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receipt];//拼接请求数据
//    //    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
//    [SLPublicNetHelper postpplePayWithReceipt:receipt WithUrl:storeURL success:^(id response, BOOL isNetData) {
//        [self dismissLoadingAnimatedToView];
//        if ([response[@"code"] integerValue]==200) {
//            [MBProgressHUD showInformation:response[@"message"] toView:WINDOW andAfterDelay:HUD_TIME];
//            [SLParamManager shareInstance].vip=YES;
//            [self.navigationController popViewControllerAnimated:YES];
//        }
//    } fail:^(NSError *error, NSURLSessionDataTask *task) {
//        [self dismissLoadingAnimatedToView];
//    }];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
